<?php
/**
 * XueYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * User controller class
 * @author Wayne Yu
 */
class Mycenter extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->library('apioutput');
		$this->load->library('msgblock');
		$this->load->helper('url');
		$uid = $this->session->userdata('uid');
		if(empty($uid)){
			redirect(site_url('login'));
		}
		$this->load->model('user_model');
		$this->load->model('user_concern_model');
		$this->load->model('user_dynamic_model');
		$this->load->model('message_letter_model');
		$this->load->model('circle_model');
		$this->load->model('topic_model');
		$this->load->model('topic_user_model');
	}
	
	/**
	 * Personal center dashboard
	 */
	public function index(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
				
		);
		$this->load->view('mycenter/mycenter',$data);
	}
	
	public function collection(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
	
		);
		$this->load->view('mycenter/mycollection',$data);
	}
	
	public function favor(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
	
		);
		$this->load->view('mycenter/myfavor',$data);
	}
	
	/**
	 * Edit user info
	 */
	public function edit(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'	=>	$userInfo,
		);
		$this->load->view('mycenter/editinfo', $data);
	}
	
	/**
	 * Edit user info
	 */
	public function editPost(){
		$input = $this->input->post();
		if(empty($input['Attribute']) || empty($input['Value'])){
			$this->apioutput->apiResponseError('非法请求，请稍后重试！');
		}
		$userData = array();
		switch ($input['Attribute']) {
			case 'title':
				$input['Value'] = json_decode($input['Value']);
				if(!is_array($input['Value']) || count($input['Value']) > 3){
					$userData[$input['Attribute']] = serialize($input['Value']);
				}
				break;
			case 'nickname':
				$res = $this->user_model->getInfo($input['Value'], 'nickname');
				if($res != FALSE){
					$this->apioutput->apiResponseError('该昵称已被占用');
				}
				$userData['nickname'] = $input['Value'];
				break;
			case 'signature':
			case 'school':
			case 'department':
			case 'class':
			case 'gender':
				$userData[$input['Attribute']] = $input['Value'];
				break;
			default:
				$this->apioutput->apiResponseError('非法请求，请稍后重试！');
		}
		
		$res = $this->user_model->updateInfo($this->session->userdata('uid'),$userData);
		if($res <= 0){
			$this->apioutput->apiResponseError('修改失败，请稍后重试！');
		}
		
		$this->apioutput->apiResponseSuccess();
	}
	
	public function uploadImg(){
		$data = array(
				'tempImg'	=>	$this->input->get('TempImg')?$this->input->get('TempImg'):'/assets/images/demo.jpg',
				'saveUrl'	=>	site_url('mycenter/saveImgPost')."?TempImg=".$this->input->get('TempImg')."&Type=".$this->input->get('Type')
		);
		$this->load->view('mycenter/uploadImg', $data);
	}
	
	/**
	 * Edit the headportrait
	 */
	public function editHeadportrait(){
		if(empty($_FILES['fulImage'])){
			die("<script>alert('上传文件不能为空');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
		}
		$nameExten = explode('.', $_FILES['fulImage']['name']);
		$type = end($nameExten);
		if(!in_array($_FILES['fulImage']['type'], array('image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/png'))){
			die("<script>alert('图片格式不正确');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
		}
		if($_FILES['fulImage']['size'] > 5*1024*1024){
			die("<script>alert('上传图片大小不能超过5M');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
		}
		
		$path = dirname(BASEPATH).'/uploads/avatar/'.$this->session->userdata('uid');
		if(!is_dir($path)){
			if(false == mkdir($path)){
				die("<script>alert('没有权限，请联系管理员');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
			}
		}
		$filepath= $path.'/temp.'.$type;
		
		if(is_uploaded_file($_FILES['fulImage']['tmp_name'])){
			if(move_uploaded_file($_FILES['fulImage']['tmp_name'], $filepath)){
				die("<script>window.location.href='".site_url('mycenter/uploadImg')."?TempImg=".'/uploads/avatar/'.$this->session->userdata('uid').'/temp.'.$type."&Type=".$type."';</script>");
			} else{
				die("<script>alert('上传图片失败请联系管理员');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
			}
		} else{
			die("<script>alert('上传图片失败请联系管理员');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
		}
	}
	

	public function saveImgPost(){
		//源路径
		$src = dirname(BASEPATH).$this->input->get('TempImg');
		if(empty($src) || !file_exists($src)){
			die("<script>alert('请先上传图片');window.location.href='".site_url('mycenter/uploadImg')."';</script>");
		}
		$size = getimagesize($src);
		$scale = 1;
		if(isset($size[0]))	$scale = $size[0]/400;
	
		$x = $this->input->post('X1') * $scale;
		$y = $this->input->post('Y1') * $scale;
		$w = $this->input->post('Width') * $scale;
		$h = $this->input->post('Height') * $scale;
	
		//第一步，根据传来的宽，高参数创建一幅图片，然后正好将截取的部分真好填充到这个区域
		$target = @imagecreatetruecolor($w,$h)
		or die("Cannot Initialize new GD image stream");
	
		//第二步，根据路径获取到源图像,用源图像创建一个image对象
		switch ($this->input->get('Type')){
			case 'png':
				$source = imagecreatefrompng($src);
				break;
			default:
				$source = imagecreatefromjpeg($src);
		}
	
		//第三步，根据传来的参数，选取源图像的一部分填充到第一步创建的图像中
		imagecopy( $target, $source, 0, 0, $x, $y, $w, $h);
	
		//第四步,保存图像
		$newPath = dirname(BASEPATH).'/uploads/avatar/'.$this->session->userdata('uid').'/';
		if(!is_dir($newPath)){
			mkdir();
		}
		$imgSrc = '/uploads/avatar/'.$this->session->userdata('uid').'/'.(microtime()*1000000).'.jpg';
		imagejpeg($target,dirname(BASEPATH).$imgSrc,100);
		$this->user_model->updateInfo($this->session->userdata('uid'), array('headportrait'=>$imgSrc));
		unlink($src);
		die("<script>alert('保存成功');window.parent.$.fancybox.close();</script>");
	}
	
	/**
	 *
	 */
	public function concern($cid){
		$data = array(
				'concern_id'	=>	$cid,
				'user_id'	=>	$this->session->userdata('uid')
		);
		$concernInfo = $this->user_model->getInfo($cid);
		if(!$concernInfo){
			$this->msgblock->addError('您申请关注的用户不存在！');
			$this->apioutput->apiResponseError('您申请关注的用户不存在！');
		}
		if($this->user_concern_model->checkIsMember($data['user_id'], $cid) == TRUE){
			$this->msgblock->addError('您已经加入过该圈，请勿重复提交申请！');
			$this->apioutput->apiResponseError('您已经加入过该圈，请勿重复提交申请！');
		}
		$res = $this->circle_user_model->createEntity($data);
		if($res <= 0){
			$this->msgblock->addError('关注失败，请稍后重试！');
			$this->apioutput->apiResponseError('关注失败，请稍后重试！');
		}
	
		$this->apioutput->apiResponseSuccess();
	}
	
	/**
	 * Setting page
	 */
	public function settings(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
				
		);
		$this->load->view('mycenter/settings', $data);
	}
	
	public function concernedMe(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
				
		);
		$this->load->view('mycenter/concernedme', $data);
	}
	
	public function myConcerned(){
		$userInfo = $this->user_model->getInfo($this->session->userdata('uid'));
		$data = array(
				'userInfo'		=>	$userInfo,
				'concernCount'	=>	$this->user_concern_model->getConcernCount($this->session->userdata('uid')),
				'fanCount'		=>	$this->user_concern_model->getFansCount($this->session->userdata('uid')),
				
		);
		$this->load->view('mycenter/myconcerned', $data);
	}
	
	/**
	 * get my conerned
	 */
	public function getMyConcerned(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
	
		$data = $this->user_concern_model->getConcerned($this->session->userdata('uid'), $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['concern_id']);
			$data[$key]['name'] = isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['concern_id']).'">'.$uInfo['nickname'].'</a>':'';
			$data[$key]['headportrait'] = '<a href="'.site_url('user/view/'.$val['concern_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>';
		}
	
		echo json_encode($data);
	}
	
	/**
	 * get fans
	 */
	public function getConcernedMe(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
	
		$data = $this->user_concern_model->getFans($this->session->userdata('uid'), $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$data[$key]['name'] = isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'';
			$data[$key]['headportrait'] = '<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>';
		}

		echo json_encode($data);
	}
	
	public function letter($lid){
		$letterInfo	= $this->message_letter_model->getInfo($lid);
		$senderId	= $letterInfo['sender_id'];
		$senderInfo  = $this->user_model->getInfo($senderId);
		$data = array(
				'senderId'	=>	$senderId,
				'senderName'=>	$senderInfo['nickname']
		);
		$this->load->view('letter/view', $data);
	}
	
	public function getUserLetter($senderId){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->message_letter_model->getSenderLetters($senderId, $this->session->userdata('uid'), $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['sender_id']);
			$data[$key]['name'] = isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['sender_id']).'">'.$uInfo['nickname'].'</a>':'';
			$data[$key]['headportrait'] = '<a href="'.site_url('user/view/'.$val['sender_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>';
			$data[$key]['date']	= $this->user_dynamic_model->getTimeFormat(strtotime($val['created_at']));
			$data[$key]['replylink']	= ($val['user_id'] ==$this->session->userdata('uid'))?'<a class="link-rep fancybox fancybox.iframe pointer">回复</a>&nbsp|':'';
			$data[$key]['letter_id']	= $val['id'];
		}
		
		echo json_encode($data);
	}
	
	public function sendLetter($receiverId){
		$uInfo  = $this->user_model->getInfo($receiverId);
		$data = array(
				'receiverId'	=>	$receiverId,
				'receiverName'	=>	$uInfo['nickname']
		);
		$this->load->view('letter/fbxSendLetter', $data);
	}
	
	public function sendLetterPost($receiverId){
		$input = $this->input->post();
		if(empty($input['content'])){
			die("<script>alert('非法请求，请联系管理员！');window.history.back();</script>");
		}

		$data = array(
				'user_id'			=>	$receiverId,
				'sender_id'			=>	$this->session->userdata('uid'),
				'content'			=>	$input['content']
		);
		
		//save
		$lid = $this->message_letter_model->createEntity($data);
		if($lid <= 0){
			die("<script>alert('创建失败，请稍后重试！');window.history.back();</script>");
		}
		
		
		die("<script>alert('私信发送成功！');window.parent.$.fancybox.close();</script>");
	}
	
	public function delLetter(){
		$input = $this->input->post();
		if(empty($input['letter_id'])){
			$this->apioutput->apiResponseError('非法请求，请稍后重试！');
		}
		$letterInfo = $this->message_letter_model->getInfo($input['letter_id']);
		if($letterInfo['user_id'] == $this->session->userdata('uid')){
			$data = array(
					'receiver_del' =>	1
			);
		} else if($letterInfo['sender_id'] == $this->session->userdata('uid')){
			$data = array(
					'sender_del'	=>	1
			);
		}
		//save
		$res = $this->message_letter_model->updateInfo($input['letter_id'] ,$data);
		if($res <= 0){
			$this->apioutput->apiResponseError('修改失败，请稍后重试！');
		}
		
		$this->apioutput->apiResponseSuccess();
	}
	
	public function getMyCollection(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->topic_user_model->getUserTopics($this->session->userdata('uid'), $pageSize, $laseItem);
		$uInfo  = $this->user_model->getInfo($this->session->userdata('uid'));
		$topicArr = array();
		foreach ($data as $key => $val){
			$tInfo  = $this->topic_model->getInfo($val['topic_id']);
			$topicArr[] = array(
					'headportrait'	=>	'<a href="'.site_url('user/view/'.$tInfo['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>',
					'name'			=>	isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$tInfo['user_id']).'">'.$uInfo['nickname'].'</a>':'',
					'title'			=>	'<a href="'.site_url('topic/view/'.$tInfo['id']).'">'.$tInfo['title'].'</a>',
					'topicphoto'	=>	($tInfo['topic_img'])?'<img src="'.$tInfo['topic_img'].'" href="'.$tInfo['topic_img'].'" class="rep-img">':'',
					'content'		=>	$tInfo['content']
			);
		}
		echo json_encode($topicArr);
	}
}